﻿using TalentDesk.Mvc.HelperClasses;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Web;
using System.Web.Mvc;
using TalentDesk.Contracts.Ef;

namespace TalentDesk.Mvc.Controllers
{
    public enum EnumMessageType
    {
        UserMessage = 1,
        ErrorMessage = 2,
        WarningMessage = 3,
        SuccessMessage = 4,
        ValidationMessage = 5,
        Bos = 0
    }
    public class BaseController : System.Web.Mvc.Controller
    {


        public ContentResult MessageBox(string p_sMessage, EnumMessageType p_eMessageType = EnumMessageType.UserMessage, string p_sLinkUrl = "", string p_sLinkText = "", string p_sExtraScript = "")
        {
            string link = "";
            string sClass = "";

            if (p_sLinkUrl != "")
            {
                link = String.Format(@"<a href=""{0}"">{1}</a>", p_sLinkUrl, p_sLinkText);
            }

            switch (p_eMessageType)
            {
                case EnumMessageType.UserMessage:
                    sClass = "infoMessage";
                    break;
                case EnumMessageType.ErrorMessage:
                    sClass = "errorMessage";
                    break;
                case EnumMessageType.WarningMessage:
                    sClass = "warningMessage";
                    break;
                case EnumMessageType.SuccessMessage:
                    sClass = "successMessage";
                    break;
                case EnumMessageType.ValidationMessage:
                    sClass = "validationMessage";
                    break;
                case EnumMessageType.Bos:
                    break;
                default:
                    break;
            }
            //            string messagePattern = String.Format(@"<div class=""{0}""><strong>{1}</strong>
            //{2}
            //                                      </div> ",sClass, p_sMessage,link);
            string messagePattern = String.Format(@"<div class=""{0}""><strong>{1}</strong>{2}</div>", sClass, p_sMessage, link);

            return Content(string.Format(@"<script language='javascript' type='text/javascript'>
                  $('#windowMessage').data('kendoWindow').content('{0}');                       
                  $('#windowMessage').data('kendoWindow').open();  {1}
</script>", messagePattern, p_sExtraScript));

        }

        protected override void OnException(ExceptionContext filterContext)
        {
            //log exception here...

            // I'm handling it.
            //base.OnException(filterContext);

            System.Diagnostics.EventLog.WriteEntry("CbeLight", filterContext.Exception.ToString(), System.Diagnostics.EventLogEntryType.Error);

            filterContext.ExceptionHandled = true;
            MyWebException theError = new MyWebException { MessageHeader = "Hata!" };

            if (filterContext.Exception.GetType() == typeof(ApplicationException))
                theError.MessageDetail = filterContext.Exception.Message;
            else if (filterContext.Exception.GetType() == typeof(CommunicationException))
                theError.MessageDetail = "Web sunucusu ve uygulama sunucusu bağlantısında problem var.";
            else
                theError.MessageDetail = "Uygulamada genel bir hata var, lütfen sistem yöneticinize başvurun";// +Environment.NewLine + filterContext.Exception.Message;

            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = this.Json(theError);
            }
            else
            {
                filterContext.Exception = new ApplicationException(theError.MessageDetail);
            }
            base.OnException(filterContext);
        }

        //protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
        //{
        //    return new MyJsonResult
        //    {
        //        Data = data,
        //        ContentType = contentType,
        //        ContentEncoding = contentEncoding,
        //        JsonRequestBehavior = behavior
        //    };

        //}


        //protected override void OnActionExecuting(ActionExecutingContext filterContext)
        //{
        //    System.Diagnostics.EventLog.WriteEntry("CbeLight", "In OnActionExecuting" +
        //        filterContext.ActionDescriptor.ActionName + "..." + filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
        //    System.Diagnostics.EventLogEntryType.Information);

        //    if ((filterContext.ActionDescriptor.ActionName == "SessionExpired") && (filterContext.ActionDescriptor.ControllerDescriptor.ControllerName == "Account"))
        //        base.OnActionExecuting(filterContext);
        //    else
        //    {

        //        if (filterContext.HttpContext.Session != null)
        //        {

        //            if (filterContext.HttpContext.Session.IsNewSession)
        //            {
        //                string cookie = filterContext.HttpContext.Request.Headers["Cookie"];

        //                if ((cookie != null) && (cookie.IndexOf("ASP.NET_SessionId") >= 0))
        //                {
        //                    System.Web.Security.FormsAuthentication.SignOut();
        //                    filterContext.Result = RedirectToAction("SessionExpired", "Account");
        //                    return;
        //                }
        //            }
        //        }
        //        base.OnActionExecuting(filterContext);
        //    }
        //}

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            if (filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AuthorizeAttribute), true) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(TalentDeskAuthorizeAttribute), true))
            {
                if (AuthenticationHelpers.GetLoggedInUser() == null)
                {
                    System.Web.Security.FormsAuthentication.SignOut();
                    filterContext.Result = RedirectToAction("SessionExpired", "Account");
                    return;
                }
            }

            base.OnActionExecuting(filterContext);
        }


    }
}